package edu.sctu.yueding.activitys;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.umeng.socialize.Config;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;

import java.util.HashMap;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.NewsCommentAdapter;
import edu.sctu.yueding.bean.HomeListViewBean;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.MetaBean;
import edu.sctu.yueding.bean.NewsBean;
import edu.sctu.yueding.bean.NewsCommentsBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.NoSlideListView;


/**
 * Created by zhengsenwen on 2016/8/3.
 */
public class ActivityDetailsActivity extends BaseActivity {

    private ImageView back;
    private Activity activity;
    private EditText editText;

    private String comments;
    private WebView webView;
    private ImageView share;
    private NoSlideListView commentList;
    private List<NewsCommentsBean> newsCommentsBeanList;
    private NewsCommentAdapter adapter = null;
    private String commentNameText;
    private SharePreference sharePreference;
    public static final String ID_TAG = "id";

    private String token;

    private String threadId;
    int position;
    private String contentURL;
    private String mShareTitle, mShareImageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_details);

        initViews();
//        showComments();
        Config.dialogSwitch = true;

    }

    private void initData(final CallBack callBack) {

        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {

                JsonBaseBeen<NewsBean> newsBean = JSON.parseObject(json, new TypeReference<JsonBaseBeen<NewsBean>>() {
                }.getType());

                if (newsBean.getMeta().getCode() == 200) {

                    newsCommentsBeanList = newsBean.getData().getComments();

                    contentURL = newsBean.getData().getContent();
                    mShareTitle = newsBean.getData().getTitle();
                    mShareImageUrl =newsBean.getData().getThumbnail();
                    token = SharePreference.getInstance(activity).getString(CacheConfig.CACHE_TOKEN);
                    threadId =newsBean.getData().getThreadId();

                    callBack.initDataFinish();

                    initAdapter();


                } else {
                    Log.e("details comments json", "Not 200 Not SUCCESS!");
                }
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.e("comments json before", "error  comments   ...");
            }
        };

        GetVolleyHttp.getInstance(activity).getStringGETJsonData(URLConfig.URL_ONE_NEWS(Integer.parseInt(getIntent
                        ().getExtras().getString(ID_TAG))),
                listener, errorListener, (long) 5000);
    }


    private void initViews() {

        activity = this;


//        contentURL = getIntent().getExtras().getString("content");
//        mShareTitle = getIntent().getExtras().getString("title");
//        mShareImageUrl = getIntent().getExtras().getString("image");
//        token = SharePreference.getInstance(activity).getString(CacheConfig.CACHE_TOKEN);
//        threadId = getIntent().getExtras().getString("threadId");
//        position = Integer.parseInt(getIntent().getExtras().getString("position"));

        editText = (EditText) findViewById(R.id.activity_details_comment);
        webView = (WebView) findViewById(R.id.activity_details_webView);
        commentList = (NoSlideListView) findViewById(R.id.news_comment_list);
        share = (ImageView) findViewById(R.id.activity_details_forward_img);
        back = (ImageView) findViewById(R.id.activity_details_back);


        sharePreference = SharePreference.getInstance(activity);
        commentNameText = sharePreference.getString(CacheConfig.CACHE_NICKNMAE);


        initData(new CallBack() {
            @Override
            public void initDataFinish() {

                back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });

                share.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        new ShareAction(ActivityDetailsActivity.this).setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                                .withTitle(mShareTitle)
                                .withText(contentURL)
                                .withMedia(new UMImage(ActivityDetailsActivity.this, mShareImageUrl))
                                .withTargetUrl(contentURL)
                                .setCallback(umShareListener)
                                .open();
                    }
                });

                publishComments();

                initWebView();
            }

        });



    }

    /**
     * 发表评论
     */
    private void publishComments() {
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    if (SharePreference.getInstance(activity).ifHaveShare(CacheConfig.CACHE_TOKEN)) {
                        comments = editText.getText().toString();
                        uploadComment();
                    } else {
                        Toast.makeText(activity, "请先登录", Toast.LENGTH_SHORT).show();
                    }

                    editText.setText("");
                    return false;
                }
                return false;
            }
        });
    }


    /**
     * 未登录状态浏览评论
     */
    private void showComments() {

        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {

                JsonBaseListBean<HomeListViewBean> homeListViewBean = JSON.parseObject(json, new TypeReference<JsonBaseListBean<HomeListViewBean>>() {
                }.getType());
                newsCommentsBeanList = homeListViewBean.getData().get(position).getComments();

                MetaBean meta = homeListViewBean.getMeta();
                if (meta.getCode() == 200 && meta.getErrorType().equals("SUCCESS")) {
                    initAdapter();
                } else {
                    Log.e("details comments json", "Not 200 Not SUCCESS!");
                }
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.e("comments json before", "error  comments   ...");
            }
        };

        GetVolleyHttp.getInstance(activity).getStringGETJsonData(URLConfig.URL_HOME_LIST,
                listener, errorListener, (long) 5000);
    }

    /**
     * 上传评论
     */
    private void uploadComment() {

        Response.Listener<String> commentListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                Log.e(" comments json after", json);

                NewsCommentsBean newsCommentsBean = new NewsCommentsBean();
                newsCommentsBean.setContent(comments);
                newsCommentsBean.setAuthorName(commentNameText);

                if (newsCommentsBeanList != null) {
                    newsCommentsBeanList.add(newsCommentsBean);
                    adapter.onDateChange(newsCommentsBeanList);
                    Toast.makeText(activity, "评论成功！", Toast.LENGTH_LONG).show();
                } else {
                    Log.e("newsCommentsBeanList", "newsCommentsBeanList is null");
                }
            }
        };

        Response.ErrorListener commentErrorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.e("comments json after", "error  comments   ...");
            }
        };

        HashMap<String, String> map = new HashMap<>();
        map.put("threadId", threadId);
        map.put("content", comments);
        map.put("parentId", String.valueOf(-1));

        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(URLConfig.URL_COMMUNITY_COMMENT,
                map, commentListener, commentErrorListener, URLConfig.BEAREAR + token);
    }

    private void initAdapter() {
        if (adapter == null) {
            adapter = new NewsCommentAdapter(activity, newsCommentsBeanList);
            commentList.setAdapter(adapter);
        } else {
            adapter.onDateChange(newsCommentsBeanList);
        }
    }

    /**
     * 对webVIew进行设置
     */
    private void initWebView() {

        webView.loadUrl(contentURL);

        webView.setWebChromeClient(new WebChromeClient() {
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(activity, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(activity, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(activity, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        Log.d("result", "onActivityResult");
    }

    interface CallBack{
        void initDataFinish();
    }

}


